package com.police.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.BDNotifyListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.Geometry;
import com.baidu.mapapi.map.Graphic;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MKOfflineMap;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.RouteOverlay;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPlanNode;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.police.PoliceApp;
import com.police.R;
import com.police.adapter.JiZhanListAdapter;
import com.police.controller.AsyncHandler;
import com.police.controller.Controller;
import com.police.controller.DefaultController;
import com.police.controller.DefaultRequest;
import com.police.controller.IRequest;
import com.police.controller.IResponse;
import com.police.controller.JSONResp;
import com.police.db.EventManager;
import com.police.db.SearchRecord;
import com.police.db.SearchRecordManager;
import com.police.db.UserManager;
import com.police.model.JiZhanListBean;
import com.police.util.Util;
import com.police.view.Click_View;
import com.police.view.GuiJiView;
import com.police.view.RadiusView;
import com.police.view.TimePop;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity {
    public static final int INT = 30000;// 定位时间间隔
    static Controller HTTP = DefaultController.getHttpClient();
    static DateFormat formate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    // MapView
    static MapView mMapView = null;
    public MKMapViewListener mMapListener = null;
    public MyLocationListenner myListener = new MyLocationListenner();
    public NotifyLister mNotifyer = null;
    MKOfflineMap mOffline = null; // 申明变量
    private Context mContext;
    // 定位相关
    LocationClient mLocClient;
    MyLocationOverlay myLocationOverlay = null;
    LocationData locData = null;
    private MapController mMapController = null;
    private Vibrator mVibrator;
    // 地址查询
    private MKSearch mSearch;
    private String city = "北京";
    private LayoutInflater inflater;
    private PopupOverlay pop;

    private ImageView homeText;

    /**
     * 轨迹相关
     */
    Symbol palaceSymbol;
    GraphicsOverlay palaceOverlay;
    List<GeoPoint> palacePoints = new ArrayList<GeoPoint>();
    /**
     * 圆心经纬度坐标
     */
    private double mLat = 39.90923;
    private double mLon = 116.357428;
    private LocOverlay ov;
    /**
     * 基站列表相关
     */
    private JiZhanListBean jiZhanListBean;
    private List<JiZhanListBean> jiZhanList = new ArrayList<JiZhanListBean>();
    private List<JiZhanListBean> whichTypeJiZhanList = new ArrayList<JiZhanListBean>();
    private LinearLayout jiZhanPopLayout;
    private ListView jiZhanListView;
    private JiZhanListAdapter jiZhanListAdapter;
    private PopupWindow jiZhanPopWidow;
    private Button jbutton;
    Symbol nbSymbol;
    /**
     * 经纬度查询popu相关
     */
    private PopupWindow jwSearchPop;
    private Button addBtn;
    private EditText jdEdit;
    private EditText wdEdit;
    private Button jwdSearchBen;
    private Button searchRecord;
    private RelativeLayout jwSearchLayout;
    private Drawable marker;
    /**
     * 地址搜索相关
     */
    private PopupWindow popuWindow;
    private View v;
    private View popuLayout;

    /**
     * 事件相关
     */
    private Button shijianBtn;

    /**
     * 设置相关
     */
    private Button setBtn;

    ProgressDialog dialog;

    /**
     * lac cid 搜索相关
     */
    private EditText lacEdit;
    private EditText cidEdit;

    /**
     * lac cid 点击十进制十六进制切换
     */
    private Button lacBtn, cidBtn;
    /**
     * 移动电信联通选择
     */
    private CheckBox yd, lt, dx;

    private PopupWindow guijiPop;
    private PopupWindow JizhanClickPop;
    private PopupWindow radiusPop;

    private static int SCALE = 12;
    private TextView biLiCiText;

    /**
     * 放比例尺缩放比例对应关系
     */
    private Map<String, String> biLiChiMap = new HashMap<String, String>();

    //距离（导航开启时距终点的距离）
    private TextView distanceValue;
    private boolean isStartDaoHang = false;
    private TextView distanceText;


    /**
     * lac cid显示相关
     */
    private TextView LACValue, CIDValue;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PoliceApp app = (PoliceApp) this.getApplication();
        if (app.mBMapMan == null) {
            app.mBMapMan = new BMapManager(this);
            app.mBMapMan.init(PoliceApp.mStrKey,
                    new PoliceApp.MyGeneralListener());
        }
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        mContext = this;
        initBiLiChi();
        initViews();
        initMapView();
        initLocClient();
        initListener();
    }

    private void initMapView() {
        mMapView = (MapView) findViewById(R.id.bmapView);
        mMapController = mMapView.getController();
        mMapView.setLongClickable(true);
        mMapView.setDoubleClickZooming(true);
        mMapController.setZoom(SCALE);
        biLiCiText.setText("1:" + biLiChiMap.get(String.valueOf(SCALE)));
        mMapController.enableClick(true);
    }

    private void initViews() {
        homeText = (ImageView) findViewById(R.id.home);
        yd = (CheckBox) findViewById(R.id.yd);
        lt = (CheckBox) findViewById(R.id.lt);
        dx = (CheckBox) findViewById(R.id.dx);
        lacBtn = (Button) findViewById(R.id.lacBtn);
        cidBtn = (Button) findViewById(R.id.cidBtn);
        shijianBtn = (Button) findViewById(R.id.shijian);
        jwdSearchBen = (Button) findViewById(R.id.jwdSearchBtn);
        searchRecord = (Button) findViewById(R.id.search_record);
        setBtn = (Button) findViewById(R.id.setBtn);
//        marker = getResources().getDrawable(R.drawable.iconmarka);
        marker = getResources().getDrawable(R.drawable.dingweimark);
        dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("正在查询数据，请稍候");
//        JizhanClickPop = jiZhanClickPopupWindow();
        radiusPop = radiusPopupWindow();

        biLiCiText = (TextView) findViewById(R.id.biLiCiText);

        distanceValue = (TextView) findViewById(R.id.distanceValue);
        distanceText = (TextView) findViewById(R.id.distanceText);

    }

    private void initLocClient() {
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        mLocClient.setLocOption(initLocationOption());
        mLocClient.start();

        mMapListener = new MKMapViewListener() {

            @Override
            public void onMapMoveFinish() {
            }

            @Override
            public void onClickMapPoi(MapPoi mapPoiInfo) {
                String title = "";
                if (mapPoiInfo != null) {
                    title = mapPoiInfo.strText;
                    Toast.makeText(MainActivity.this, title, Toast.LENGTH_SHORT)
                            .show();
                }
            }

            @Override
            public void onGetCurrentMap(Bitmap b) {

            }

            @Override
            public void onMapAnimationFinish() {

            }
        };
        mMapView.regMapViewListener(PoliceApp.App.mBMapMan, mMapListener);
        myLocationOverlay = new MyLocationOverlay(mMapView);
        locData = new LocationData();
        myLocationOverlay.setData(locData);
        mMapView.getOverlays().add(myLocationOverlay);
        myLocationOverlay.enableCompass();
        mMapView.refresh();
        pop = new PopupOverlay(mMapView, popListener);

        palaceSymbol = getSymbol(1);
        palaceOverlay = new GraphicsOverlay(mMapView);
        // 将overlay添加到mapview中
        mMapView.getOverlays().add(palaceOverlay);

        nbSymbol = getSymbol(0);
        ov = new LocOverlay(marker, this, mMapView);
        ov.setPop(pop);
        mMapView.getOverlays().add(ov);

        // 初始化搜索模块，注册事件监听
        mSearch = new MKSearch();
        mSearch.init(PoliceApp.App.mBMapMan, new MKSearchListener() {

            @Override
            public void onGetPoiDetailSearchResult(int type, int error) {
                if (error != 0) {
                    Toast.makeText(MainActivity.this, "抱歉，未找到结果",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "成功，查看详情页面",
                            Toast.LENGTH_SHORT).show();
                }
            }

            public void onGetPoiResult(MKPoiResult res, int type, int error) {
                // 错误号可参考MKEvent中的定义
                if (error != 0 || res == null) {
                    Toast.makeText(MainActivity.this, "抱歉，未找到结果",
                            Toast.LENGTH_LONG).show();
                    return;
                }
                // 将地图移动到第一个POI中心点
                if (res.getCurrentNumPois() > 0) {
                    // 将poi结果显示到地图上
                    AdressPoiOverlay poiOverlay = new AdressPoiOverlay(
                            MainActivity.this, mMapView, mSearch);
                    poiOverlay.setData(res.getAllPoi());
                    mMapView.getOverlays().clear();
                    mMapView.getOverlays().add(poiOverlay);
                    mMapView.refresh();
                    // 当ePoiType为2（公交线路）或4（地铁线路）时， poi坐标为空
                    for (MKPoiInfo info : res.getAllPoi()) {
                        if (info.pt != null) {
                            mMapView.getController().animateTo(info.pt);
                            break;
                        }
                    }
                } else if (res.getCityListNum() > 0) {
                    String strInfo = "在";
                    for (int i = 0; i < res.getCityListNum(); i++) {
                        strInfo += res.getCityListInfo(i).city;
                        strInfo += ",";
                    }
                    strInfo += "找到结果";
                    Toast.makeText(MainActivity.this, strInfo,
                            Toast.LENGTH_LONG).show();
                }
            }

            public void onGetDrivingRouteResult(MKDrivingRouteResult res,
                                                int error) {
                if (res == null) {
                    return;
                }
                RouteOverlay routeOverlay = new RouteOverlay(MainActivity.this,
                        mMapView); // 此处仅展示一个方案作为示例
                routeOverlay.setData(res.getPlan(0).getRoute(0));
                mMapView.getOverlays().add(routeOverlay);
                mMapView.refresh();
            }

            public void onGetTransitRouteResult(MKTransitRouteResult res,
                                                int error) {

            }

            public void onGetWalkingRouteResult(MKWalkingRouteResult res,
                                                int error) {

            }

            public void onGetAddrResult(MKAddrInfo res, int error) {
            }

            public void onGetBusDetailResult(MKBusLineResult result, int iError) {
            }

            @Override
            public void onGetSuggestionResult(MKSuggestionResult res, int arg1) {

            }

        });
    }

    public void searchRoute(GeoPoint pt) {
        MKPlanNode start = new MKPlanNode();
        start.pt = new GeoPoint((int) (mLat * 1E6), (int) (mLon * 1E6));
        MKPlanNode end = new MKPlanNode();//GeoPoint: Latitude: 31117842, Longitude: 121249765 GeoPoint: Latitude: 31122599, Longitude: 121257194
        end.pt = pt;// 设置驾车路线搜索策略，时间优先、费用最少或距离最短GeoPoint: Latitude: 31117842, Longitude: 121249765
        mSearch.setDrivingPolicy(MKSearch.ECAR_TIME_FIRST);
        mSearch.drivingSearch(null, start, null, end);
        isStartDaoHang = true;
        distanceValue.setVisibility(View.VISIBLE);
        distanceText.setVisibility(View.VISIBLE);
        //导航终点选择后，设置当前的距离
//		double distance = getDaoHangDistance(start.pt,end.pt);//26508.706071615365
        double distance = Util.getDistance(mLat, mLon, end.pt.getLatitudeE6() / 1000000.0, end.pt.getLongitudeE6() / 1000000.0);
        distanceValue.setText(getDistance(distance) + "km");
        if (distance <= 1) {
            showDialog("当前位置距离终点不到一公里！");
        }
        SharedPreferences.Editor editor = preference.edit();
        editor.putInt("lat", end.pt.getLatitudeE6()).commit();
        editor.putInt("lng", end.pt.getLongitudeE6()).commit();

        /**
         * 计算起点与终点间的直线距离
         */

    }

    @Override
    protected void onStart() {
        super.onStart();
        PoliceApp app = (PoliceApp) this.getApplication();
        app.mBMapMan.start();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        PoliceApp app = (PoliceApp) this.getApplication();
        app.mBMapMan.stop();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mMapView.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        if (mLocClient != null)
            mLocClient.stop();
        mMapView.destroy();
        PoliceApp app = (PoliceApp) this.getApplication();
        if (app.mBMapMan != null) {
            app.mBMapMan.destroy();
            app.mBMapMan = null;
        }
        super.onDestroy();
    }

    // 设置相关参数
    private LocationClientOption initLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        // option.setProdName("Police");
        option.setPoiExtraInfo(true);
        option.setAddrType("all");
        option.setCoorType("bd09ll");// 设置坐标类型,百度坐标
        option.setScanSpan(INT);// 设置定位模式，小于1秒则一次定位;大于等于1秒则定时定位
        // option.setPriority(LocationClientOption.NetWorkFirst); // 设置网络优先
        // option.setPoiNumber(10);默認3
        option.disableCache(true);
        return option;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (this.getResources().getConfiguration()
                .equals(Configuration.ORIENTATION_LANDSCAPE)) {
            // L
        } else if (this.getResources().getConfiguration()
                .equals(Configuration.ORIENTATION_PORTRAIT)) {
            // P
        }
    }

    private void initListener() {

        homeText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                goHome();
            }
        });

        // 事件监听
        shijianBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // // TODO Auto-generated method stub
                // if (preference.getBoolean("isAdmin", false)) {
                //
                // /**
                // * 管理员登陆，首先显示办事人员列表
                // */
                // UserManager userManager = new UserManager(helper);
                // //查询出办事人员
                // shiJianBeanList = userManager.query();
                // showPopupWindow(shijianBtn, 280, -400);
                // } else {
                //
                // /**
                // * 非管理员，显示当前登录用户的事件列表
                // */
                // // showDialog("正在查找...");loginUserName
                // EventManager eventManager = new EventManager(helper);
                // itemOneBeanList =
                // eventManager.queryPresentUserEvent(preference.getString("loginUserName",
                // ""));
                // showpopuWindowEventOneItem(shijianBtn, 280, -400);
                // }

                // TODO Auto-generated method stub
                if (preference.getBoolean("isAdmin", false)) {

                    /**
                     * 管理员登陆，首先显示办事人员列表
                     */
                    UserManager userManager = new UserManager(helper);
                    // 查询出办事人员
                    shiJianBeanList = userManager.query();
                    showPopupWindow(shijianBtn, 280, -380);
                } else {

                    /**
                     * 非管理员，显示当前登录用户的事件列表
                     */
                    // showDialog("正在查找...");loginUserName
                    EventManager eventManager = new EventManager(helper);
                    itemOneBeanList = eventManager
                            .queryPresentUserEvent(preference.getString(
                                    "loginUserName", ""));
                    showpopuWindowEventOneItem(shijianBtn, 280, -380);
                }

            }
        });

        // 基站列表
        jbutton = (Button) this.findViewById(R.id.j);
        jbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jiZhanList.clear();
                whichTypeJiZhanList.clear();

                onNB(mLon, mLat);
            }
        });

        // 基站搜索
        Button sbutton = (Button) this.findViewById(R.id.search);
        sbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.show();
                DefaultRequest request = new DefaultRequest("qryPoint");
                lacEdit = (EditText) MainActivity.this
                        .findViewById(R.id.lacEdit);
                cidEdit = (EditText) MainActivity.this
                        .findViewById(R.id.cidEdit);
                if (lacEdit.getText().toString() != null
                        && cidEdit.getText().toString() != null) {
                    final String lac = lacEdit.getText().toString();
                    final String cid = cidEdit.getText().toString();
                    request.putParam("lac", lac);
                    request.putParam("cid", cid);
                    final String id = lac + "," + cid;
                    HTTP.post(request, new AsyncHandler() {

                        @Override
                        public void onStart() {
                            // TODO Auto-generated method stub
                            // PublicTool.getIntence(mContext).showDialog(
                            // "正在搜索基站信息...");
                            super.onStart();
                        }

                        @Override
                        public void onSuccess(JSONResp response) {
                            try {
                                Toast.makeText(MainActivity.this,
                                        response.getString("info"), 5000)
                                        .show();
                                int result = response.getInt("result");
                                if (IResponse.Success == result) {// 获取基站列表数据成功
                                    if (dialog != null) {

                                        dialog.dismiss();
                                    }
                                    // data:[{mnc:'基站类型',lac:'基站号',cellid:'小区号',lon:'经度',lat:'纬度',range:'覆盖范围'},{mnc:'基站类型',lac:'基站号',cellid:'小区号',lon:'经度',lat:'纬度',range:'覆盖范围'}]}
                                    JSONArray cells = response
                                            .getJSONArray("data");
                                    showNB(cells, id);
                                    saveSearchRecord(lac, cid);
                                }
                            } catch (JSONException e) {
                                Log.e("qryPoint", e.getMessage());
                            }
                            PublicTool.getIntence(mContext).missDialog();

                            super.onSuccess(response);
                        }
                    });
                }

            }
        });

        this.findViewById(R.id.dingwei).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (!mLocClient.isStarted()) {
                            mLocClient.start();
                        }
                        mLocClient.requestLocation();

                        myLocationOverlay.setData(locData);
                        mMapView.refresh();
                        mMapController.animateTo(new GeoPoint(
                                (int) (locData.latitude * 1e6),
                                (int) (locData.longitude * 1e6)));
                    }
                });

        /**
         * 经纬度查询按钮监听
         */
        jwdSearchBen.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                showJwdSeachPopu();

            }
        });

        /**
         * 弹出搜索记录
         */
        searchRecord.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.e("弹出pop", "弹出pop");
                if (preference.getBoolean("isAdmin", false)) {
                    // 如果是管理员，显示出搜索人员的列表
                    /**
                     * 管理员登陆，首先显示办事人员列表
                     */
                    UserManager userManager = new UserManager(helper);
                    // 查询出办事人员
                    shiJianBeanList = userManager.query();
                    showpopuWindowSearchUsers(searchRecord, 280, -33);
                } else {
                    com.police.db.SearchRecordManager searchRecordManager = new com.police.db.SearchRecordManager(
                            helper);
                    searchRecordList = searchRecordManager.query(preference
                            .getString("loginUserName", ""));
                    if (searchRecordList.size() == 0) {
                        Toast.makeText(MainActivity.this, "该人员没有搜索记录", 6000)
                                .show();
                    } else {
                        showSearchRecordPopu(searchRecord, 300, 36);
                    }
                }
            }
        });

        // 地址
        this.findViewById(R.id.addSearchBtn).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showSearchWayPopupWindow(view, 220, -315);

                    }
                });

        // 设置监听
        setBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (preference.getBoolean("isAdmin", false)) {
                    UserManager userManager = new UserManager(helper);
                    shiJianBeanList = userManager.query();
                    if (3 <= shiJianBeanList.size()) {
                        showpopuWindowSetItem(v, 575, 190);
                    } else if (shiJianBeanList.size() == 0) {
                        showpopuWindowSetItem(v, 380, 190);
                    } else if (shiJianBeanList.size() == 1) {
                        showpopuWindowSetItem(v, 440, 190);
                    } else if (shiJianBeanList.size() == 2) {
                        showpopuWindowSetItem(v, 485, 190);
                    }

                } else {
                    showpopuWindowSetItem(v, 380, 190);
                }
            }
        });
        // 轨迹
        this.findViewById(R.id.guiji).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow();
            }
        });
        // 比例尺
        final SeekBar seekBar = (SeekBar) (this.findViewById(R.id.seek));
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                int level = (int) ((i * 0.01 * 17 + 3) % 17);
                mMapView.getController().setZoom(level);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        this.findViewById(R.id.jia).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                seekBar.setProgress(seekBar.getProgress() - 6);


                if (SCALE > 3) {
                    SCALE--;
//					mMapView.getController().zoomOut();
                    mMapView.getController().setZoom(SCALE);
                    biLiCiText.setText("1:" + biLiChiMap.get(String.valueOf(SCALE)));
                }
            }
        });
        this.findViewById(R.id.jian).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                seekBar.setProgress(seekBar.getProgress() + 6);


                if (SCALE < 18) {
                    SCALE++;
//					mMapView.getController().zoomOut();
                    mMapView.getController().setZoom(SCALE);
                    biLiCiText.setText("1:" + biLiChiMap.get(String.valueOf(SCALE)));
                }

//				mMapView.getController().zoomIn();
            }
        });

        /**
         * 点击十进制和16进制切换
         */
        lacBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (lacBtn.getText().toString().equals("LAC10")) {
                    lacBtn.setText("LAC16");
                    cidBtn.setText("CID16");
                } else if (lacBtn.getText().toString().equals("LAC16")) {
                    cidBtn.setText("CID10");
                    lacBtn.setText("LAC10");
                }
            }
        });
        cidBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (cidBtn.getText().toString().equals("CID10")) {
                    lacBtn.setText("LAC16");
                    cidBtn.setText("CID16");
                } else if (cidBtn.getText().toString().equals("CID16")) {
                    cidBtn.setText("CID10");
                    lacBtn.setText("LAC10");
                }
            }
        });
    }

    private void onGuiji(String bt, String et) {
        DefaultRequest request = new DefaultRequest("qryLoc");
        // deviceid=设备号&bt=开始时间&et=结束时间
        request.putParam("deviceid", "abc-12345678-00003");
        request.putParam("bt", bt);
        request.putParam("et", et);
        dialog.show();

        HTTP.post(request, new AsyncHandler() {
            @Override
            public void onSuccess(JSONResp response) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                try {
                    Toast.makeText(MainActivity.this,
                            response.getString("info"), 5000).show();
                    int result = response.getInt("result");
                    if (IResponse.Success == result) {// 获取基站列表数据成功
                        // {result:'结果状态',info:'结果描述',data:[{gpstime:'GPS时间',lon:'经度',lat:'纬度'},{gpstime:'GPS时间',lon:'经度',lat:'纬度'}]}
                        JSONArray gpsdata = response.getJSONArray("data");
                        showGuiji(gpsdata);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                super.onSuccess(response);
            }
        });
    }

    private void showGuiji(JSONArray gpsdata) {
        if (gpsdata != null && gpsdata.length() != 0) {
            for (int index = 0; index < gpsdata.length(); index++) {
                try {
                    JSONObject gpsObj = (JSONObject) gpsdata.get(index);
                    Util.GPS gps = Util.transform(new Util.GPS(gpsObj
                            .getDouble("lon"), gpsObj.getDouble("lat")));
                    palacePoints.add(new GeoPoint((int) (gps.lat * 1E6),
                            (int) (gps.lon * 1E6)));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            refreshGuiji();

        }

    }

    private void onNB(double mLon, double mLat) {
        DefaultRequest request = new DefaultRequest("qryCell");
        Util.GPS gps = Util.bd_decrypt(mLon, mLat);

        request.putParam("lon", gps.lon);
        request.putParam("lat", gps.lat);

        HTTP.post(request, new AsyncHandler() {
            @Override
            public void onStart() {
                super.onStart();
                dialog.show();
            }

            @Override
            public void onSuccess(JSONResp response) {
                try {
                    Toast.makeText(MainActivity.this,
                            response.getString("info"), 5000).show();
                    int result = response.getInt("result");
                    if (IResponse.Success == result) {// 获取基站列表数据成功

                        if (dialog != null) {

                            dialog.dismiss();
                        }
                        // data:[{mnc:'基站类型',lac:'基站号',cellid:'小区号',lon:'经度',lat:'纬度',range:'覆盖范围'},{mnc:'基站类型',lac:'基站号',cellid:'小区号',lon:'经度',lat:'纬度',range:'覆盖范围'}]}
//                        JSONArray cells = response.getJSONArray("data");
//                        showNB(cells,null);

                        /**
                         * 显示基站列表
                         */
                        showJiZhanList(response);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                super.onSuccess(response);
            }
        });
    }

    private void refreshGuiji() {
        Geometry palaceGeometry = new Geometry();
        palaceGeometry.setPolyLine(palacePoints
                .toArray(new GeoPoint[palacePoints.size()]));
        // 创建Graphic对象
        Graphic palaceGraphic = new Graphic(palaceGeometry, palaceSymbol);
        /**
         * 向GraphicsOverlay添加Graphic 一个GraphicsOVerlay可添加多个Graphic
         * GraphicsOVerlay的remove接口使用setData()返回的ID来移除指定Graphic
         */
        long palaceId = palaceOverlay.setData(palaceGraphic);
        // 刷新地图使新添加的overlay生效
        mMapView.refresh();
        // 移动，缩放地图到最视野
        // mMapView.getController().setZoom(10);
        mMapView.getController().setCenter(
                palacePoints.get(palacePoints.size() - 1));
    }

    private Symbol getSymbol(int mark) {
        Symbol circleSymbol = new Symbol();
        Symbol.Color circleColor = circleSymbol.new Color();
        circleColor.red = 0;
        circleColor.green = 255;
        circleColor.blue = 0;
        circleColor.alpha = 200;
        circleSymbol.setSurface(circleColor, mark, 3);
        return circleSymbol;
    }

    /**
     * 显示"查询方式窗口..."窗口
     *
     * @param v
     */
    public void showSearchWayPopupWindow(View v, int height, int fromX) {

        if (popuWindow == null) {
            initPopupWindow(v, height);
        }
        if (popuWindow.isShowing()) {
            popuWindow.dismiss();
        } else {
            popuWindow.update();
            popuWindow.showAtLocation(v, Gravity.TOP, fromX, 92);
        }
    }

    /**
     * 输入地址定位功能
     */
    private void initPopupWindow(View view1, int height) {
        popuWindow = new PopupWindow(initaddressLayout(), 350, height);
        popuWindow.setAnimationStyle(R.style.PopuAnimation);
        popuWindow.setFocusable(true);
        popuWindow.setBackgroundDrawable(new BitmapDrawable());
    }

    public View initaddressLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        popuLayout = (View) inflater.inflate(R.layout.input_address_populayout,
                null);
        final EditText addressEdit = (EditText) popuLayout
                .findViewById(R.id.addressEdit);
        Button sureBtn = (Button) popuLayout.findViewById(R.id.sureBtn);
        sureBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (popuWindow != null && popuWindow.isShowing()) {
                    popuWindow.dismiss();
                }
                clearMapView();
                mSearch.poiSearchInCity(city, addressEdit.getText().toString());

            }
        });
        return popuLayout;
    }

    /**
     * 经纬度查询
     */
    private void showJwdSeachPopu() {

        // if (jwSearchPop == null) {
        // initJwSearchPopupWindow(230);
        // }
        // if (jwSearchPop.isShowing()) {
        // jwSearchPop.dismiss();
        // } else {
        // jwSearchPop.update();
        // jwSearchPop.showAtLocation(jwdSearchBen, Gravity.TOP, -400, 45);
        // }

        if (jwSearchPop == null) {
            initJwSearchPopupWindow(320);
        }
        if (jwSearchPop.isShowing()) {
            jwSearchPop.dismiss();
        } else {
            jwSearchPop.update();
            jwSearchPop.showAtLocation(jwdSearchBen, Gravity.TOP, -375, 92);
        }

    }

    private void initJwSearchPopupWindow(int height) {
        jwSearchPop = new PopupWindow(initJwSearchLayout(), 500, height);
        jwSearchPop.setAnimationStyle(R.style.PopuAnimation);
        jwSearchPop.setFocusable(true);
        jwSearchPop.setBackgroundDrawable(new BitmapDrawable());

    }

    public RelativeLayout initJwSearchLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        jwSearchLayout = (RelativeLayout) inflater.inflate(
                R.layout.jwd_search_pop_layout, null);

        jdEdit = (EditText) jwSearchLayout.findViewById(R.id.jdEdit);
        wdEdit = (EditText) jwSearchLayout.findViewById(R.id.wdEdit);

        addBtn = (Button) jwSearchLayout.findViewById(R.id.addBtn);

        addBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (jwSearchPop != null && jwSearchPop.isShowing()) {
                    jwSearchPop.dismiss();
                }
                clearMapView();
                GeoPoint point = new GeoPoint((int) (Double.parseDouble(jdEdit
                        .getText().toString()) * 1E6), (int) (Double
                        .parseDouble(wdEdit.getText().toString()) * 1E6));
                OverlayItem item = new OverlayItem(point, jdEdit.getText()
                        .toString(), wdEdit.getText().toString());
                item.setMarker(marker);
                ov.addItem(item);
                // mMapView.getOverlays().add(ov);
                mMapView.refresh();
                if (point != null)
                    mMapView.getController().animateTo(point);

            }
        });

        return jwSearchLayout;
    }

    /**
     * {"lon":121.407,"cellid":57730,"mnc":0,"range":574,"lat":31.1781,"lac":
     * 6180}
     * <p/>
     * {mnc:'基站类型',lac:'基站号',cellid:'小区号',lon:'经度',lat:'纬度',range:'覆盖范围'}
     * <p/>
     * <p/>
     * {"data":[{"lon":121.407,"cellid":57730,"mnc":0,"range":574,"lat":31.1781,
     * "lac":6180},
     * {"lon":121.407,"cellid":45329,"mnc":0,"range":672,"lat":31.1787
     * ,"lac":6264},
     * {"lon":121.408,"cellid":307,"mnc":0,"range":574,"lat":31.1795,"lac":6264}
     */
    private void showJiZhanList(JSONResp response) {
        // TODO Auto-generated method stub
        try {
            Gson gson = new Gson();
            Type type = new TypeToken<List<JiZhanListBean>>() {
            }.getType(); // 指定集合对象属性
            List<JiZhanListBean> fromJson = gson.fromJson(
                    response.getString("data"), type);
            jiZhanList.addAll(fromJson);
            if (jiZhanList.size() != 0) {
                if (yd.isChecked() && lt.isChecked() && dx.isChecked()) {
                    for (int i = 0; i < jiZhanList.size(); i++) {
                        whichTypeJiZhanList.add(jiZhanList.get(i));
                    }
                } else if (yd.isChecked() && !lt.isChecked() && !dx.isChecked()) {
                    for (int i = 0; i < jiZhanList.size(); i++) {
                        if (jiZhanList.get(i).getMnc().equals("0")) {
                            whichTypeJiZhanList.add(jiZhanList.get(i));
                        }
                    }
                } else if (!yd.isChecked() && lt.isChecked() && !dx.isChecked()) {
                    for (int i = 0; i < jiZhanList.size(); i++) {
                        if (jiZhanList.get(i).getMnc().equals("1")) {
                            whichTypeJiZhanList.add(jiZhanList.get(i));
                        }
                    }
                } else if (!yd.isChecked() && !lt.isChecked() && dx.isChecked()) {
                    for (int i = 0; i < jiZhanList.size(); i++) {
                        if (jiZhanList.get(i).getMnc().equals("2")) {
                            whichTypeJiZhanList.add(jiZhanList.get(i));
                        }
                    }
                } else if (yd.isChecked() && lt.isChecked() && !dx.isChecked()) {
                    for (int i = 0; i < jiZhanList.size(); i++) {
                        if (!jiZhanList.get(i).getMnc().equals("2")) {
                            whichTypeJiZhanList.add(jiZhanList.get(i));
                        }
                    }
                } else if (yd.isChecked() && !lt.isChecked() && dx.isChecked()) {
                    for (int i = 0; i < jiZhanList.size(); i++) {
                        if (!jiZhanList.get(i).getMnc().equals("1")) {
                            whichTypeJiZhanList.add(jiZhanList.get(i));
                        }
                    }
                } else if (!yd.isChecked() && lt.isChecked() && dx.isChecked()) {
                    for (int i = 0; i < jiZhanList.size(); i++) {
                        if (!jiZhanList.get(i).getMnc().equals("0")) {
                            whichTypeJiZhanList.add(jiZhanList.get(i));
                        }
                    }
                }
                if (whichTypeJiZhanList.size() == 0) {
                    Toast.makeText(mContext, "没有该基站信息", 6000).show();
                } else {
                    showJiZhanMap(whichTypeJiZhanList);
                    showJiZhanPopu();
                }
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

        }
    }

    private void showJiZhanMap(List<JiZhanListBean> whichTypeJiZhanList) {
        clearMapView();
        GeoPoint point = null;
        for (JiZhanListBean bean : whichTypeJiZhanList) {
            Util.GPS gps = Util.transform(new Util.GPS(Double.valueOf(bean.getLon()), Double.valueOf(bean.getLat())));
            point = new GeoPoint((int) (gps.lat * 1E6),
                    (int) (gps.lon * 1E6));
            String id = bean.getLac() + "," + bean.getCellid();

            OverlayItem item = new OverlayItem(point, id, "" + circle(point, preference.getInt("banJin", 700)));
            item.setMarker(marker);
            ov.addItem(item);
        }
//            mMapView.getOverlays().add(palaceOverlay);
//            mMapView.getOverlays().add(ov);
        mMapView.refresh();
        if (point != null)
            mMapView.getController().animateTo(point);
    }

    private void showJiZhanPopu() {

        if (jiZhanPopWidow == null) {
            initJiZhanPopupWindow(400);
        }
        if (jiZhanPopWidow.isShowing()) {
            jiZhanPopWidow.dismiss();
        } else {
            jiZhanPopWidow.update();
            jiZhanPopWidow.showAtLocation(jbutton, Gravity.BOTTOM, -90, 68);
        }

    }

    /**
     * 基站pop
     *
     * @param height
     */
    private void initJiZhanPopupWindow(int height) {

        jiZhanPopWidow = new PopupWindow(initJiZhanListLayout(), 720, height);
        jiZhanPopWidow.setAnimationStyle(R.style.menuPopupAnimation);
        jiZhanPopWidow.setFocusable(true);
        jiZhanPopWidow.setBackgroundDrawable(new BitmapDrawable());
    }

    /**
     * 基站列表
     *
     * @return
     */
    public LinearLayout initJiZhanListLayout() {
        inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        jiZhanPopLayout = (LinearLayout) inflater.inflate(
                R.layout.jizhan_list_view, null);
        jiZhanListView = (ListView) jiZhanPopLayout
                .findViewById(R.id.jizhan_list);
        final Button sign = (Button) jiZhanPopLayout.findViewById(R.id.sign);
        sign.setText("标记基站");
        sign.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                /**
                 * 点击事件
                 */
                if (sign.getText().equals("标记基站")) {
                    sign.setText("取消标记");
                    for (OverlayItem item : ov.getAllItem()) {
                        palaceOverlay.removeGraphic(Long
                                .valueOf(item
                                        .getSnippet()));
                    }
                } else if (sign.getText().equals("取消标记")) {
                    sign.setText("标记基站");
                    for (OverlayItem item : ov.getAllItem()) {
                        GeoPoint point = item.getPoint();
                        item.setMarker(marker);
                        ov.removeItem(new OverlayItem(point, item.getTitle(), "" + circle(point, preference.getInt("banjin", 700))));
                        ov.addItem(item);
                    }
                }
                mMapView.refresh();

            }
        });
        jiZhanListAdapter = new JiZhanListAdapter(this, whichTypeJiZhanList);
        jiZhanListAdapter.setOnDataItemDeleted(new JiZhanListAdapter.OnDataItemDeleted() {
            @Override
            public void notifyDataItemDeleted(int pos) {
                ov.removeItem(ov.getItem(pos));
                mMapView.refresh();
            }
        });
        jiZhanListView.setAdapter(jiZhanListAdapter);

        return jiZhanPopLayout;
    }

    private void showNB(JSONArray cells, String id) throws JSONException {
        clearMapView();
        if (cells != null && cells.length() != 0) {
            GeoPoint point = null;
            for (int index = 0; index < cells.length(); index++) {
                JSONObject cell = (JSONObject) cells.get(index);
                Util.GPS gps = Util.transform(new Util.GPS(cell
                        .getDouble("lon"), cell.getDouble("lat")));
                point = new GeoPoint((int) (gps.lat * 1E6),
                        (int) (gps.lon * 1E6));
                // String mnc = cell.getString("mnc");
                if (id == null) {
                    id = cell.getString("lac") + "," + cell.getString("cellid");
                }
                OverlayItem item = new OverlayItem(point, id, "" + preference.getInt("banJin", 700));
                item.setMarker(marker);
                ov.addItem(item);
            }
//            mMapView.getOverlays().add(palaceOverlay);
//            mMapView.getOverlays().add(ov);
            mMapView.refresh();
            if (point != null)
                mMapView.getController().animateTo(point);
        } else {
            Toast.makeText(this, "没有搜索到基站数据", Toast.LENGTH_SHORT).show();
        }
    }

    private long circle(GeoPoint point, int range) {
        Geometry palaceGeometry = new Geometry();
        palaceGeometry.setCircle(point, range);
        // 创建Graphic对象
        Graphic palaceGraphic = new Graphic(palaceGeometry, nbSymbol);
        long palaceId = palaceOverlay.setData(palaceGraphic);
        return palaceId;

    }

    /**
     * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return;
            city = location.getCity();
            mLat = locData.latitude = location.getLatitude();
            mLon = locData.longitude = location.getLongitude();
            locData.accuracy = location.getRadius();
            locData.direction = location.getDerect();
            // deviceid=设备号&gpstime=GPS时间&lon=经度&lat=纬度
            final IRequest request = new DefaultRequest("addLoc");
            request.putParam("deviceid", "abc-12345678-00003");// 登陆时要保存设备ID
            request.putParam("gpstime", System.currentTimeMillis());
            request.putParam("lon", locData.longitude);
            request.putParam("lat", locData.latitude);
            /**
             * 每30秒上报当前位置，并改变距离
             */

            if (distanceValue != null && isStartDaoHang) {
                double distance = Util.getDistance(mLat, mLon, preference.getInt("lat", 0) / 1000000.0, preference.getInt("lng", 0) / 1000000.0);
                distanceValue.setText(getDistance(distance) + "km");
                if (distance <= 1) {
                    //跳出对话框预警，当前离终点位置不到1km
                    showDialog("当前位置距离终点不到一公里！");
                }
            }


            DefaultController.getHttpClient().post(request, new AsyncHandler() {
                @Override
                public void onSuccess(JSONResp response) {
                    int result = 0;
                    try {
                        result = response.getInt("result");
                        if (IResponse.Success == result) {
                            Log.i("GPS", request.toParams());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    super.onSuccess(response);
                }
            });

            // mLocClient.stop();
        }

        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null) {
                return;
            }
        }
    }

    public class NotifyLister extends BDNotifyListener {

        public void onNotify(BDLocation mlocation, float distance) {
        }
    }

    public void popupWindow() {
        clearMapView();
        palacePoints.clear();
        final GuiJiView popup = new GuiJiView(this);
        guijiPop = createWin(popup);
        guijiPop.showAtLocation(this.findViewById(R.id.guiji), Gravity.BOTTOM,
                -500, 68);
        guijiPop.getContentView().findViewById(R.id.play)
                .setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String[] times = popup.getTimes();
                        onGuiji(times[0], times[1]);
                        Log.e("times[0]", times[0] + "....");
                    }
                });

        final TextView startTime = (TextView) guijiPop.getContentView().findViewById(R.id.time_start);
        final TextView endTime = (TextView) guijiPop.getContentView().findViewById(R.id.time_end);
        startTime.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                TimePopupWindow(startTime);
            }
        });
        ((TextView) guijiPop.getContentView().findViewById(R.id.time_start))
                .setText("开始时间");

        endTime.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                TimePopupWindow(endTime);
            }
        });

        ((SeekBar) (guijiPop.getContentView().findViewById(R.id.control)))
                .setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int i,
                                                  boolean b) {

                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {

                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        String[] times = popup.getTimes();
                        onGuiji(times[0], times[1]);
                    }

                });

        guijiPop.update();
    }

    private void clearMapView() {
        if (ov != null)
            ov.removeAll();
        if (palaceOverlay != null)
            palaceOverlay.removeAll();
        mMapView.refresh();
    }

    private PopupWindow createWin(final GuiJiView popup) {

        final int ScreenHeight = getWindowManager().getDefaultDisplay()
                .getHeight();
        final int ScreenWidth = getWindowManager().getDefaultDisplay()
                .getWidth();
        final PopupWindow win = new PopupWindow(popup, ScreenWidth,
                ScreenHeight);

        win.setWidth(android.view.WindowManager.LayoutParams.WRAP_CONTENT);
        win.setHeight(android.view.WindowManager.LayoutParams.WRAP_CONTENT);

        win.setFocusable(true);
        win.setBackgroundDrawable(new BitmapDrawable());
        win.setOutsideTouchable(false);

        return win;
    }

    /**
     * 将搜索记录添加到数据库
     */
    private void saveSearchRecord(String lac, String cid) {
        // 将当前搜索成功时所搜索的LAC CID保存到数据库
        if (lac != null && cid != null) {
            Date dataTime = new Date();
            SimpleDateFormat simpleFormat = new SimpleDateFormat(
                    "yyyy-MM-dd hh:mm:ss");
            SearchRecord searchRecord = new SearchRecord(preference.getString(
                    "loginUserName", ""), simpleFormat.format(dataTime), lac,
                    cid);
            SearchRecordManager searchRecordManager = new SearchRecordManager(
                    helper);
            searchRecordManager.add(searchRecord);
        }

    }

    /**
     * 创建一个popupoverlay
     */
    PopupClickListener popListener = new PopupClickListener() {
        @Override
        public void onClickedPopup(int index) {
            if (index == 0) {
                // 更新item位置
                pop.hidePop();
                OverlayItem mCurItem = ov.getCurItem();
                GeoPoint p = new GeoPoint(
                        mCurItem.getPoint().getLatitudeE6() + 5000, mCurItem
                        .getPoint().getLongitudeE6() + 5000);
                // JizhanClickPop.showAsDropDown(jwdSearchBen, 150, 400);
                JizhanClickPop = jiZhanClickPopupWindow(mCurItem);
                JizhanClickPop.showAtLocation(jwdSearchBen, Gravity.CENTER, 0,
                        430);
                mMapView.refresh();
            }

        }
    };

    private PopupWindow radiusPopupWindow() {
        RadiusView pop = new RadiusView(mContext);
        radiusPop = new PopupWindow(pop, 300, 600);
        radiusPop.setFocusable(true);
        radiusPop.setBackgroundDrawable(new BitmapDrawable());
        return radiusPop;
    }

    private void missJiZhanClickPop() {
        if (JizhanClickPop != null && JizhanClickPop.isShowing()) {
            JizhanClickPop.dismiss();
        }
    }

    /**
     * 点击基站弹出pop
     */

    public PopupWindow jiZhanClickPopupWindow(OverlayItem mCurItem) {
        Click_View pop = new Click_View(mContext);
        JizhanClickPop = new PopupWindow(pop, 300, 600);
        JizhanClickPop.setFocusable(true);
        JizhanClickPop.setBackgroundDrawable(new BitmapDrawable());


        if (mCurItem != null) {
            final OverlayItem curItem = ov.getCurItem();
//            palaceOverlay.removeGraphic(Long
//                    .valueOf(curItem
//                            .getSnippet()));
            final String[] lc = curItem.getTitle().split(",");

            LACValue = (TextView) pop.findViewById(R.id.LACValue);
            LACValue.setText(lc[0]);

            CIDValue = (TextView) pop.findViewById(R.id.CIDValue);
            CIDValue.setText(lc[1]);

//            request.putParam("lac", lc[0]);
//            request.putParam("cid", lc[1]);
        }


        pop.findViewById(R.id.daohang).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        missJiZhanClickPop();
                        searchRoute(ov.getCurItem().getPoint());
                    }
                });

        pop.findViewById(R.id.delete).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                missJiZhanClickPop();
                ov.removeItem(ov.getCurItem());
                mMapView.refresh();
            }
        });
        pop.findViewById(R.id.area).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                missJiZhanClickPop();
                radiusPop.getContentView().findViewById(R.id.jwdSearchBtn)
                        .setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (ov != null && ov.getCurItem() != null
                                        && ov.getCurItem().getSnippet() != null) {
                                    OverlayItem curItem = ov.getCurItem();
                                    View contentView = radiusPop
                                            .getContentView();
                                    String s = ((TextView) (contentView
                                            .findViewById(R.id.input_radius)))
                                            .getText().toString();
                                    if (s != null) {
                                        palaceOverlay.removeGraphic(Long
                                                .valueOf(curItem
                                                        .getSnippet()));
                                        GeoPoint point = curItem.getPoint();
                                        OverlayItem item = new OverlayItem(point, curItem.getTitle(), "" + circle(point, Integer.valueOf(s)));
                                        item.setMarker(marker);
                                        ov.removeItem(curItem);
                                        ov.addItem(item);
//                                        mMapView.getOverlays().add(
//                                                palaceOverlay);
//                                        mMapView.getOverlays().add(ov);
                                        mMapView.refresh();
                                    }

                                }
                            }
                        });

            }
        });
        pop.findViewById(R.id.jizhan).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                missJiZhanClickPop();
                if (ov != null && ov.getCurItem() != null) {
                    GeoPoint point = ov.getCurItem().getPoint();
                    onNB(point.getLongitudeE6() / 1e6,
                            point.getLatitudeE6() / 1e6);
                }
            }
        });

        pop.findViewById(R.id.xiangdao).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                missJiZhanClickPop();
                if (ov != null && ov.getCurItem() != null) {
                    final OverlayItem curItem = ov.getCurItem();
                    palaceOverlay.removeGraphic(Long
                            .valueOf(curItem
                                    .getSnippet()));
                    final String[] lc = curItem.getTitle().split(",");
                    DefaultRequest request = new DefaultRequest("qryCellByCell");
                    request.putParam("lac", lc[0]);
                    request.putParam("cid", lc[1]);
                    HTTP.post(request, new AsyncHandler() {

                        @Override
                        public void onStart() {
                            // TODO Auto-generated method stub
                            // PublicTool.getIntence(mContext).showDialog(
                            // "正在搜索基站信息...");
                            super.onStart();
                        }

                        @Override
                        public void onSuccess(JSONResp response) {
                            try {
                                Toast.makeText(MainActivity.this,
                                        response.getString("info"), 5000)
                                        .show();
                                int result = response.getInt("result");
                                if (IResponse.Success == result) {// 获取基站列表数据成功
                                    if (dialog != null) {
                                        dialog.dismiss();
                                    }
                                    // data:[{mnc:'基站类型',lac:'基站号',cellid:'小区号',lon:'经度',lat:'纬度',range:'覆盖范围'},{mnc:'基站类型',lac:'基站号',cellid:'小区号',lon:'经度',lat:'纬度',range:'覆盖范围'}]}
                                    JSONArray cells = response
                                            .getJSONArray("data");
                                    saveSearchRecord(lc[0], lc[1]);
                                    showXiaodao(curItem, cells);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            PublicTool.getIntence(mContext).missDialog();

                            super.onSuccess(response);
                        }
                    });
                }
            }
        });

        return JizhanClickPop;
    }

    private void showXiaodao(OverlayItem curItem, JSONArray cells) {
        GeoPoint center = curItem.getPoint();
        if (cells == null || cells.length() == 0) {
            Toast.makeText(this, "没有搜索到基站热点数据", Toast.LENGTH_SHORT).show();
            return;
        }
        int length = cells.length();
        final String[] lc = curItem.getTitle().split(",");
        String lac = lc[0];
        String cid = lc[1];
        GeoPoint[] points = new GeoPoint[length + 1];
        points[0] = curItem.getPoint();
        int i = 1;
        try {
            for (int index = 0; index < length; index++) {
                points[i++] = gpsPoint((JSONObject) cells.get(index));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OverlayItem item = new OverlayItem(center, curItem.getTitle(), "" + sector(center, points));
        item.setMarker(marker);
        ov.addItem(item);
//        mMapView.getOverlays().add(palaceOverlay);
//        mMapView.getOverlays().add(ov);
        mMapView.refresh();
    }

    private GeoPoint gpsPoint(JSONObject cell) throws JSONException {
        Util.GPS gps1 = Util.transform(new Util.GPS(cell
                .getDouble("lon"), cell.getDouble("lat")));
        return new GeoPoint((int) (gps1.lat * 1E6),
                (int) (gps1.lon * 1E6));
    }

    private long sector(GeoPoint point, GeoPoint[] points) {
        Geometry palaceGeometry = new Geometry();
        palaceGeometry.setPolyLine(points);
        // 创建Graphic对象
        Graphic palaceGraphic = new Graphic(palaceGeometry, this.nbSymbol);
        long palaceId = palaceOverlay.setData(palaceGraphic);
        return palaceId;

    }


    private void goHome() {
        Intent i = new Intent(Intent.ACTION_MAIN);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addCategory(Intent.CATEGORY_HOME);
        startActivity(i);
    }

    public PopupWindow timePopupWindow;

    public void TimePopupWindow(TextView timeTextView) {
        TimePop pop = new TimePop(this, timeTextView);
        timePopupWindow = createTimeWin(pop);
        timePopupWindow.showAtLocation(this.findViewById(R.id.guiji),
                Gravity.BOTTOM, -500, 122);

    }

    private PopupWindow createTimeWin(TimePop timePop) {
        // TODO Auto-generated method stub
        final int ScreenHeight = getWindowManager().getDefaultDisplay()
                .getHeight();
        final int ScreenWidth = getWindowManager().getDefaultDisplay()
                .getWidth();
        final PopupWindow win = new PopupWindow(timePop, 715,
                300);

//		win.setWidth(android.view.WindowManager.LayoutParams.WRAP_CONTENT);
//		win.setHeight(android.view.WindowManager.LayoutParams.WRAP_CONTENT);

        win.setFocusable(true);
        win.setBackgroundDrawable(new BitmapDrawable());
        win.setOutsideTouchable(false);

        return win;

    }


    private void initBiLiChi() {
        biLiChiMap.put("3", "50");
        biLiChiMap.put("4", "100");
        biLiChiMap.put("5", "200");
        biLiChiMap.put("6", "500");
        biLiChiMap.put("7", "1000");
        biLiChiMap.put("8", "2000");
        biLiChiMap.put("9", "5000");
        biLiChiMap.put("10", "10000");
        biLiChiMap.put("11", "20000");
        biLiChiMap.put("12", "25000");
        biLiChiMap.put("13", "50000");
        biLiChiMap.put("14", "100000");
        biLiChiMap.put("15", "200000");
        biLiChiMap.put("16", "500000");
        biLiChiMap.put("17", "1000000");
        biLiChiMap.put("18", "2000000");
    }

}
